package com.github.postsanf.yinian.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.utils.UIHelper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.utils.Log;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class PicWallShareActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private ImageView btn_share_wx_timeline;
    private ImageView btn_share_wx_friend;
    private ImageView btn_share_qq_timeline;
    private ImageView btn_share_qq;
    private UMShareAPI mShareAPI;
    private String urlSec;
    private String title;
    private String avaUrl;
    private File f;
    private ImageView iv_qrcode;
    private ProgressDialog mProgressDialog;
    private RelativeLayout rl_share;
    private String qRcode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_picwall_share);
        mShareAPI = UMShareAPI.get(this);
        urlSec = getIntent().getStringExtra("uelSec");
        title = getIntent().getStringExtra("title");
        avaUrl = getIntent().getStringExtra("avaUrl");
        initView();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.today_share_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        final String[] mPermissionList = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS};
        ActivityCompat.requestPermissions(PicWallShareActivity.this, mPermissionList, 100);
        btn_share_wx_timeline = (ImageView) findViewById(R.id.btn_share_wx_timeline);
        btn_share_wx_friend = (ImageView) findViewById(R.id.btn_share_wx_friend);
        btn_share_qq_timeline = (ImageView) findViewById(R.id.btn_share_qq_timeline);
        btn_share_qq = (ImageView) findViewById(R.id.btn_share_qq);
        btn_share_wx_timeline.setOnClickListener(this);
        btn_share_wx_friend.setOnClickListener(this);
        btn_share_qq_timeline.setOnClickListener(this);
        btn_share_qq.setOnClickListener(this);

        //图片二维码分享
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        ImageView iv_pic = ((ImageView) findViewById(R.id.iv_pic));
        iv_qrcode = ((ImageView) findViewById(R.id.iv_qrcode));
        TextView qr_code = ((TextView) findViewById(R.id.qr_code));
        rl_share = ((RelativeLayout) findViewById(R.id.rl_share));
        TextView tv_above = (TextView) findViewById(R.id.tv_above);
        qRcode = getIntent().getStringExtra("QRcode");
        if (qRcode != null && qRcode.equals("QRcode")) {
            String firstPic = getIntent().getStringExtra("firstPic");
            String nickName = getIntent().getStringExtra("nickName");
            String qRtext = getIntent().getStringExtra("QRtext");
            String above = getIntent().getStringExtra("above");
            if (above != null) {
                tv_above.setText(above);
            }
            tv_title.setText(nickName);
            qr_code.setText(qRtext);

            ImageLoader.getInstance().displayImage(firstPic, iv_pic, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    mProgressDialog = ProgressDialog.show(PicWallShareActivity.this, "", "正在为您合成图片...");
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    String urlShare = getIntent().getStringExtra("UrlShare");
                    createQRImage(urlShare, UIHelper.dip2px(PicWallShareActivity.this, 120), UIHelper.dip2px(PicWallShareActivity.this, 120));
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });

        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 朋友圈
            case R.id.btn_share_wx_timeline:
                if (qRcode != null && qRcode.equals("QRcode")) {
                    saveBitmap(rl_share, 7);
                } else {
                    UMWeb web = new UMWeb(urlSec);
                    web.setTitle(title);//标题
                    web.setThumb(new UMImage(PicWallShareActivity.this, avaUrl));  //缩略图
                    web.setDescription("宝宝所有的秘密都在这里了");//描述
                    new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                            .withMedia(web)
                            .share();
                }
                Intent statintent = new Intent(ACTIONs.record);
                statintent.putExtra("key", "eventFriendCircle_6");
                statintent.putExtra("value", 1);
                sendBroadcast(statintent);
                break;
            // 微信好友
            case R.id.btn_share_wx_friend:
                if (qRcode != null && qRcode.equals("QRcode")) {
                    saveBitmap(rl_share, 6);
                } else {
                    UMWeb webf = new UMWeb(urlSec);
                    webf.setTitle(title);//标题
                    webf.setThumb(new UMImage(this, avaUrl));  //缩略图
                    webf.setDescription("宝宝所有的秘密都在这里了");//描述
                    new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                            .withMedia(webf)
                            .share();
                }
                Intent statintentfriend = new Intent(ACTIONs.record);
                statintentfriend.putExtra("key", "eventWechat_6");
                statintentfriend.putExtra("value", 1);
                sendBroadcast(statintentfriend);
                break;
            // qq空间
            case R.id.btn_share_qq_timeline:
                if (qRcode != null && qRcode.equals("QRcode")) {
                    saveBitmap(rl_share, 9);
                } else {
                    UMWeb webzone = new UMWeb(urlSec);
                    webzone.setTitle(title);//标题
                    webzone.setThumb(new UMImage(this, avaUrl));  //缩略图
                    webzone.setDescription("宝宝所有的秘密都在这里了");//描述
                    new ShareAction(this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                            .withMedia(webzone)
                            .share();
                }
                Intent statintentzone = new Intent(ACTIONs.record);
                statintentzone.putExtra("key", "eventQZone_6");
                statintentzone.putExtra("value", 1);
                sendBroadcast(statintentzone);
                break;
            case R.id.btn_share_qq:
                if (qRcode != null && qRcode.equals("QRcode")) {
                    saveBitmap(rl_share, 8);
                } else {
                    UMWeb webqq = new UMWeb(urlSec);
                    webqq.setTitle(title);//标题
                    webqq.setThumb(new UMImage(this, avaUrl));  //缩略图
                    webqq.setDescription("宝宝所有的秘密都在这里了");//描述
                    new ShareAction(this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                            .withMedia(webqq)
                            .share();
                }
                Intent statintentqq = new Intent(ACTIONs.record);
                statintentqq.putExtra("key", "eventQQ_6");
                statintentqq.putExtra("value", 1);
                sendBroadcast(statintentqq);
                break;
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(PicWallShareActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(PicWallShareActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(PicWallShareActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("yuhao", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(PicWallShareActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }


    public void saveBitmap(View v, int flag) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        f = new File(file.getPath() + "/", System.currentTimeMillis() + ".png");
        if (f.exists()) {
            f.delete();
        }
        Bitmap bm = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        v.draw(canvas);
//        try {
//            FileOutputStream out = new FileOutputStream(f);
//            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
//            out.flush();
//            out.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        if (flag == 6) {
            new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withMedia(new UMImage(this, bm))
                    .share();
        } else if (flag == 7) {
            new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withMedia(new UMImage(this, bm))
                    .share();
        } else if (flag == 8) {
            new ShareAction(this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                    .withMedia(new UMImage(this, bm))
                    .share();
        } else {
            new ShareAction(this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                    .withText("忆年")
//                    .withTitle("忆年")
//                    .withTargetUrl(getResources().getString(R.string.APP_LOADURL))
                    .withMedia(new UMImage(this, bm))
                    .share();
        }
    }

    private void createQRImage(String content, int widthPix, int heightPix) {
        try {
            if (content == null || "".equals(content)) {
                return;
            }
            //配置参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //设置空白边距的宽度
            hints.put(EncodeHintType.MARGIN, 2); //default is 4
            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
            iv_qrcode.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        //隐藏照片墙的分享选择
        sendBroadcast(new Intent(ACTIONs.gone));
        mProgressDialog.dismiss();
    }

    // 友盟统计
    public void onResume() {
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
